home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / doctest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  75.3 KB  |  2,284 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Module doctest -- a framework for running examples in docstrings.
  5.  
  6. In simplest use, end each module M to be tested with:
  7.  
  8. def _test():
  9.     import doctest
  10.     doctest.testmod()
  11.  
  12. if __name__ == "__main__":
  13.     _test()
  14.  
  15. Then running the module as a script will cause the examples in the
  16. docstrings to get executed and verified:
  17.  
  18. python M.py
  19.  
  20. This won\'t display anything unless an example fails, in which case the
  21. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  22. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  23. line of output is "Test failed.".
  24.  
  25. Run it with the -v switch instead:
  26.  
  27. python M.py -v
  28.  
  29. and a detailed report of all examples tried is printed to stdout, along
  30. with assorted summaries at the end.
  31.  
  32. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  33. it by passing "verbose=False".  In either of those cases, sys.argv is not
  34. examined by testmod.
  35.  
  36. There are a variety of other ways to run doctests, including integration
  37. with the unittest framework, and support for running non-Python text
  38. files containing doctests.  There are also many ways to override parts
  39. of doctest\'s default behaviors.  See the Library Reference Manual for
  40. details.
  41. '''
  42. __docformat__ = 'reStructuredText en'
  43. __all__ = [
  44.     'register_optionflag',
  45.     'DONT_ACCEPT_TRUE_FOR_1',
  46.     'DONT_ACCEPT_BLANKLINE',
  47.     'NORMALIZE_WHITESPACE',
  48.     'ELLIPSIS',
  49.     'SKIP',
  50.     'IGNORE_EXCEPTION_DETAIL',
  51.     'COMPARISON_FLAGS',
  52.     'REPORT_UDIFF',
  53.     'REPORT_CDIFF',
  54.     'REPORT_NDIFF',
  55.     'REPORT_ONLY_FIRST_FAILURE',
  56.     'REPORTING_FLAGS',
  57.     'Example',
  58.     'DocTest',
  59.     'DocTestParser',
  60.     'DocTestFinder',
  61.     'DocTestRunner',
  62.     'OutputChecker',
  63.     'DocTestFailure',
  64.     'UnexpectedException',
  65.     'DebugRunner',
  66.     'testmod',
  67.     'testfile',
  68.     'run_docstring_examples',
  69.     'Tester',
  70.     'DocTestSuite',
  71.     'DocFileSuite',
  72.     'set_unittest_reportflags',
  73.     'script_from_examples',
  74.     'testsource',
  75.     'debug_src',
  76.     'debug']
  77. import __future__
  78. import sys
  79. import traceback
  80. import inspect
  81. import linecache
  82. import os
  83. import re
  84. import unittest
  85. import difflib
  86. import pdb
  87. import tempfile
  88. import warnings
  89. from StringIO import StringIO
  90. OPTIONFLAGS_BY_NAME = { }
  91.  
  92. def register_optionflag(name):
  93.     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  94.  
  95. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  96. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  97. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  98. ELLIPSIS = register_optionflag('ELLIPSIS')
  99. SKIP = register_optionflag('SKIP')
  100. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  101. COMPARISON_FLAGS = DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | SKIP | IGNORE_EXCEPTION_DETAIL
  102. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  103. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  104. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  105. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  106. REPORTING_FLAGS = REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE
  107. BLANKLINE_MARKER = '<BLANKLINE>'
  108. ELLIPSIS_MARKER = '...'
  109.  
  110. def _extract_future_flags(globs):
  111.     '''
  112.     Return the compiler-flags associated with the future features that
  113.     have been imported into the given namespace (globs).
  114.     '''
  115.     flags = 0
  116.     for fname in __future__.all_feature_names:
  117.         feature = globs.get(fname, None)
  118.         if feature is getattr(__future__, fname):
  119.             flags |= feature.compiler_flag
  120.             continue
  121.     
  122.     return flags
  123.  
  124.  
  125. def _normalize_module(module, depth = 2):
  126.     '''
  127.     Return the module specified by `module`.  In particular:
  128.       - If `module` is a module, then return module.
  129.       - If `module` is a string, then import and return the
  130.         module with that name.
  131.       - If `module` is None, then return the calling module.
  132.         The calling module is assumed to be the module of
  133.         the stack frame at the given depth in the call stack.
  134.     '''
  135.     if inspect.ismodule(module):
  136.         return module
  137.     elif isinstance(module, (str, unicode)):
  138.         return __import__(module, globals(), locals(), [
  139.             '*'])
  140.     elif module is None:
  141.         return sys.modules[sys._getframe(depth).f_globals['__name__']]
  142.     else:
  143.         raise TypeError('Expected a module, string, or None')
  144.  
  145.  
  146. def _load_testfile(filename, package, module_relative):
  147.     if module_relative:
  148.         package = _normalize_module(package, 3)
  149.         filename = _module_relative_path(package, filename)
  150.         if hasattr(package, '__loader__'):
  151.             if hasattr(package.__loader__, 'get_data'):
  152.                 return (package.__loader__.get_data(filename), filename)
  153.             
  154.         
  155.     
  156.     return (open(filename).read(), filename)
  157.  
  158.  
  159. def _indent(s, indent = 4):
  160.     '''
  161.     Add the given number of space characters to the beginning every
  162.     non-blank line in `s`, and return the result.
  163.     '''
  164.     return re.sub('(?m)^(?!$)', indent * ' ', s)
  165.  
  166.  
  167. def _exception_traceback(exc_info):
  168.     '''
  169.     Return a string containing a traceback message for the given
  170.     exc_info tuple (as returned by sys.exc_info()).
  171.     '''
  172.     excout = StringIO()
  173.     (exc_type, exc_val, exc_tb) = exc_info
  174.     traceback.print_exception(exc_type, exc_val, exc_tb, file = excout)
  175.     return excout.getvalue()
  176.  
  177.  
  178. class _SpoofOut(StringIO):
  179.     
  180.     def getvalue(self):
  181.         result = StringIO.getvalue(self)
  182.         if result and not result.endswith('\n'):
  183.             result += '\n'
  184.         
  185.         if hasattr(self, 'softspace'):
  186.             del self.softspace
  187.         
  188.         return result
  189.  
  190.     
  191.     def truncate(self, size = None):
  192.         StringIO.truncate(self, size)
  193.         if hasattr(self, 'softspace'):
  194.             del self.softspace
  195.         
  196.  
  197.  
  198.  
  199. def _ellipsis_match(want, got):
  200.     """
  201.     Essentially the only subtle case:
  202.     >>> _ellipsis_match('aa...aa', 'aaa')
  203.     False
  204.     """
  205.     if ELLIPSIS_MARKER not in want:
  206.         return want == got
  207.     
  208.     ws = want.split(ELLIPSIS_MARKER)
  209.     if not len(ws) >= 2:
  210.         raise AssertionError
  211.     startpos = 0
  212.     endpos = len(got)
  213.     w = ws[0]
  214.     if w:
  215.         if got.startswith(w):
  216.             startpos = len(w)
  217.             del ws[0]
  218.         else:
  219.             return False
  220.     
  221.     w = ws[-1]
  222.     if w:
  223.         if got.endswith(w):
  224.             endpos -= len(w)
  225.             del ws[-1]
  226.         else:
  227.             return False
  228.     
  229.     if startpos > endpos:
  230.         return False
  231.     
  232.     for w in ws:
  233.         startpos = got.find(w, startpos, endpos)
  234.         if startpos < 0:
  235.             return False
  236.         
  237.         startpos += len(w)
  238.     
  239.     return True
  240.  
  241.  
  242. def _comment_line(line):
  243.     '''Return a commented form of the given line'''
  244.     line = line.rstrip()
  245.     if line:
  246.         return '# ' + line
  247.     else:
  248.         return '#'
  249.  
  250.  
  251. class _OutputRedirectingPdb(pdb.Pdb):
  252.     '''
  253.     A specialized version of the python debugger that redirects stdout
  254.     to a given stream when interacting with the user.  Stdout is *not*
  255.     redirected when traced code is executed.
  256.     '''
  257.     
  258.     def __init__(self, out):
  259.         self._OutputRedirectingPdb__out = out
  260.         pdb.Pdb.__init__(self, stdout = out)
  261.  
  262.     
  263.     def trace_dispatch(self, *args):
  264.         save_stdout = sys.stdout
  265.         sys.stdout = self._OutputRedirectingPdb__out
  266.         
  267.         try:
  268.             return pdb.Pdb.trace_dispatch(self, *args)
  269.         finally:
  270.             sys.stdout = save_stdout
  271.  
  272.  
  273.  
  274.  
  275. def _module_relative_path(module, path):
  276.     if not inspect.ismodule(module):
  277.         raise TypeError, 'Expected a module: %r' % module
  278.     
  279.     if path.startswith('/'):
  280.         raise ValueError, 'Module-relative files may not have absolute paths'
  281.     
  282.     if hasattr(module, '__file__'):
  283.         basedir = os.path.split(module.__file__)[0]
  284.     elif module.__name__ == '__main__':
  285.         if len(sys.argv) > 0 and sys.argv[0] != '':
  286.             basedir = os.path.split(sys.argv[0])[0]
  287.         else:
  288.             basedir = os.curdir
  289.     else:
  290.         raise ValueError("Can't resolve paths relative to the module " + module + ' (it has no __file__)')
  291.     return os.path.join(basedir, *path.split('/'))
  292.  
  293.  
  294. class Example:
  295.     """
  296.     A single doctest example, consisting of source code and expected
  297.     output.  `Example` defines the following attributes:
  298.  
  299.       - source: A single Python statement, always ending with a newline.
  300.         The constructor adds a newline if needed.
  301.  
  302.       - want: The expected output from running the source code (either
  303.         from stdout, or a traceback in case of exception).  `want` ends
  304.         with a newline unless it's empty, in which case it's an empty
  305.         string.  The constructor adds a newline if needed.
  306.  
  307.       - exc_msg: The exception message generated by the example, if
  308.         the example is expected to generate an exception; or `None` if
  309.         it is not expected to generate an exception.  This exception
  310.         message is compared against the return value of
  311.         `traceback.format_exception_only()`.  `exc_msg` ends with a
  312.         newline unless it's `None`.  The constructor adds a newline
  313.         if needed.
  314.  
  315.       - lineno: The line number within the DocTest string containing
  316.         this Example where the Example begins.  This line number is
  317.         zero-based, with respect to the beginning of the DocTest.
  318.  
  319.       - indent: The example's indentation in the DocTest string.
  320.         I.e., the number of space characters that preceed the
  321.         example's first prompt.
  322.  
  323.       - options: A dictionary mapping from option flags to True or
  324.         False, which is used to override default options for this
  325.         example.  Any option flags not contained in this dictionary
  326.         are left at their default value (as specified by the
  327.         DocTestRunner's optionflags).  By default, no options are set.
  328.     """
  329.     
  330.     def __init__(self, source, want, exc_msg = None, lineno = 0, indent = 0, options = None):
  331.         if not source.endswith('\n'):
  332.             source += '\n'
  333.         
  334.         if want and not want.endswith('\n'):
  335.             want += '\n'
  336.         
  337.         if exc_msg is not None and not exc_msg.endswith('\n'):
  338.             exc_msg += '\n'
  339.         
  340.         self.source = source
  341.         self.want = want
  342.         self.lineno = lineno
  343.         self.indent = indent
  344.         if options is None:
  345.             options = { }
  346.         
  347.         self.options = options
  348.         self.exc_msg = exc_msg
  349.  
  350.  
  351.  
  352. class DocTest:
  353.     '''
  354.     A collection of doctest examples that should be run in a single
  355.     namespace.  Each `DocTest` defines the following attributes:
  356.  
  357.       - examples: the list of examples.
  358.  
  359.       - globs: The namespace (aka globals) that the examples should
  360.         be run in.
  361.  
  362.       - name: A name identifying the DocTest (typically, the name of
  363.         the object whose docstring this DocTest was extracted from).
  364.  
  365.       - filename: The name of the file that this DocTest was extracted
  366.         from, or `None` if the filename is unknown.
  367.  
  368.       - lineno: The line number within filename where this DocTest
  369.         begins, or `None` if the line number is unavailable.  This
  370.         line number is zero-based, with respect to the beginning of
  371.         the file.
  372.  
  373.       - docstring: The string that the examples were extracted from,
  374.         or `None` if the string is unavailable.
  375.     '''
  376.     
  377.     def __init__(self, examples, globs, name, filename, lineno, docstring):
  378.         """
  379.         Create a new DocTest containing the given examples.  The
  380.         DocTest's globals are initialized with a copy of `globs`.
  381.         """
  382.         if not not isinstance(examples, basestring):
  383.             raise AssertionError, 'DocTest no longer accepts str; use DocTestParser instead'
  384.         self.examples = examples
  385.         self.docstring = docstring
  386.         self.globs = globs.copy()
  387.         self.name = name
  388.         self.filename = filename
  389.         self.lineno = lineno
  390.  
  391.     
  392.     def __repr__(self):
  393.         if len(self.examples) == 0:
  394.             examples = 'no examples'
  395.         elif len(self.examples) == 1:
  396.             examples = '1 example'
  397.         else:
  398.             examples = '%d examples' % len(self.examples)
  399.         return '<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)
  400.  
  401.     
  402.     def __cmp__(self, other):
  403.         if not isinstance(other, DocTest):
  404.             return -1
  405.         
  406.         return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other)))
  407.  
  408.  
  409.  
  410. class DocTestParser:
  411.     '''
  412.     A class used to parse strings containing doctest examples.
  413.     '''
  414.     _EXAMPLE_RE = re.compile('\n        # Source consists of a PS1 line followed by zero or more PS2 lines.\n        (?P<source>\n            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line\n            (?:\\n           [ ]*  \\.\\.\\. .*)*)  # PS2 lines\n        \\n?\n        # Want consists of any non-blank lines that do not start with PS1.\n        (?P<want> (?:(?![ ]*$)    # Not a blank line\n                     (?![ ]*>>>)  # Not a line starting with PS1\n                     .*$\\n?       # But any other line\n                  )*)\n        ', re.MULTILINE | re.VERBOSE)
  415.     _EXCEPTION_RE = re.compile("\n        # Grab the traceback header.  Different versions of Python have\n        # said different things on the first traceback line.\n        ^(?P<hdr> Traceback\\ \\(\n            (?: most\\ recent\\ call\\ last\n            |   innermost\\ last\n            ) \\) :\n        )\n        \\s* $                # toss trailing whitespace on the header.\n        (?P<stack> .*?)      # don't blink: absorb stuff until...\n        ^ (?P<msg> \\w+ .*)   #     a line *starts* with alphanum.\n        ", re.VERBOSE | re.MULTILINE | re.DOTALL)
  416.     _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
  417.     
  418.     def parse(self, string, name = '<string>'):
  419.         '''
  420.         Divide the given string into examples and intervening text,
  421.         and return them as a list of alternating Examples and strings.
  422.         Line numbers for the Examples are 0-based.  The optional
  423.         argument `name` is a name identifying this string, and is only
  424.         used for error messages.
  425.         '''
  426.         string = string.expandtabs()
  427.         min_indent = self._min_indent(string)
  428.         output = []
  429.         (charno, lineno) = (0, 0)
  430.         for m in self._EXAMPLE_RE.finditer(string):
  431.             output.append(string[charno:m.start()])
  432.             lineno += string.count('\n', charno, m.start())
  433.             (source, options, want, exc_msg) = self._parse_example(m, name, lineno)
  434.             if not self._IS_BLANK_OR_COMMENT(source):
  435.                 output.append(Example(source, want, exc_msg, lineno = lineno, indent = min_indent + len(m.group('indent')), options = options))
  436.             
  437.             lineno += string.count('\n', m.start(), m.end())
  438.             charno = m.end()
  439.         
  440.         output.append(string[charno:])
  441.         return output
  442.  
  443.     
  444.     def get_doctest(self, string, globs, name, filename, lineno):
  445.         '''
  446.         Extract all doctest examples from the given string, and
  447.         collect them into a `DocTest` object.
  448.  
  449.         `globs`, `name`, `filename`, and `lineno` are attributes for
  450.         the new `DocTest` object.  See the documentation for `DocTest`
  451.         for more information.
  452.         '''
  453.         return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
  454.  
  455.     
  456.     def get_examples(self, string, name = '<string>'):
  457.         '''
  458.         Extract all doctest examples from the given string, and return
  459.         them as a list of `Example` objects.  Line numbers are
  460.         0-based, because it\'s most common in doctests that nothing
  461.         interesting appears on the same line as opening triple-quote,
  462.         and so the first interesting line is called "line 1" then.
  463.  
  464.         The optional argument `name` is a name identifying this
  465.         string, and is only used for error messages.
  466.         '''
  467.         return _[1]
  468.  
  469.     
  470.     def _parse_example(self, m, name, lineno):
  471.         """
  472.         Given a regular expression match from `_EXAMPLE_RE` (`m`),
  473.         return a pair `(source, want)`, where `source` is the matched
  474.         example's source code (with prompts and indentation stripped);
  475.         and `want` is the example's expected output (with indentation
  476.         stripped).
  477.  
  478.         `name` is the string's name, and `lineno` is the line number
  479.         where the example starts; both are used for error messages.
  480.         """
  481.         indent = len(m.group('indent'))
  482.         source_lines = m.group('source').split('\n')
  483.         self._check_prompt_blank(source_lines, indent, name, lineno)
  484.         self._check_prefix(source_lines[1:], ' ' * indent + '.', name, lineno)
  485.         source = []([ sl[indent + 4:] for sl in source_lines ])
  486.         want = m.group('want')
  487.         want_lines = want.split('\n')
  488.         self._check_prefix(want_lines, ' ' * indent, name, lineno + len(source_lines))
  489.         want = []([ wl[indent:] for wl in want_lines ])
  490.         m = self._EXCEPTION_RE.match(want)
  491.         options = self._find_options(source, name, lineno)
  492.         return (source, options, want, exc_msg)
  493.  
  494.     _OPTION_DIRECTIVE_RE = re.compile('#\\s*doctest:\\s*([^\\n\\\'"]*)$', re.MULTILINE)
  495.     
  496.     def _find_options(self, source, name, lineno):
  497.         """
  498.         Return a dictionary containing option overrides extracted from
  499.         option directives in the given source string.
  500.  
  501.         `name` is the string's name, and `lineno` is the line number
  502.         where the example starts; both are used for error messages.
  503.         """
  504.         options = { }
  505.         for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  506.             option_strings = m.group(1).replace(',', ' ').split()
  507.             for option in option_strings:
  508.                 if option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME:
  509.                     raise ValueError('line %r of the doctest for %s has an invalid option: %r' % (lineno + 1, name, option))
  510.                 
  511.                 flag = OPTIONFLAGS_BY_NAME[option[1:]]
  512.                 options[flag] = option[0] == '+'
  513.             
  514.         
  515.         if options and self._IS_BLANK_OR_COMMENT(source):
  516.             raise ValueError('line %r of the doctest for %s has an option directive on a line with no example: %r' % (lineno, name, source))
  517.         
  518.         return options
  519.  
  520.     _INDENT_RE = re.compile('^([ ]*)(?=\\S)', re.MULTILINE)
  521.     
  522.     def _min_indent(self, s):
  523.         '''Return the minimum indentation of any non-blank line in `s`'''
  524.         indents = [ len(indent) for indent in self._INDENT_RE.findall(s) ]
  525.  
  526.     
  527.     def _check_prompt_blank(self, lines, indent, name, lineno):
  528.         '''
  529.         Given the lines of a source string (including prompts and
  530.         leading indentation), check to make sure that every prompt is
  531.         followed by a space character.  If any line is not followed by
  532.         a space character, then raise ValueError.
  533.         '''
  534.         for i, line in enumerate(lines):
  535.             if len(line) >= indent + 4 and line[indent + 3] != ' ':
  536.                 raise ValueError('line %r of the docstring for %s lacks blank after %s: %r' % (lineno + i + 1, name, line[indent:indent + 3], line))
  537.                 continue
  538.         
  539.  
  540.     
  541.     def _check_prefix(self, lines, prefix, name, lineno):
  542.         '''
  543.         Check that every line in the given list starts with the given
  544.         prefix; if any line does not, then raise a ValueError.
  545.         '''
  546.         for i, line in enumerate(lines):
  547.             if line and not line.startswith(prefix):
  548.                 raise ValueError('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (lineno + i + 1, name, line))
  549.                 continue
  550.         
  551.  
  552.  
  553.  
  554. class DocTestFinder:
  555.     '''
  556.     A class used to extract the DocTests that are relevant to a given
  557.     object, from its docstring and the docstrings of its contained
  558.     objects.  Doctests can currently be extracted from the following
  559.     object types: modules, functions, classes, methods, staticmethods,
  560.     classmethods, and properties.
  561.     '''
  562.     
  563.     def __init__(self, verbose = False, parser = DocTestParser(), recurse = True, exclude_empty = True):
  564.         '''
  565.         Create a new doctest finder.
  566.  
  567.         The optional argument `parser` specifies a class or
  568.         function that should be used to create new DocTest objects (or
  569.         objects that implement the same interface as DocTest).  The
  570.         signature for this factory function should match the signature
  571.         of the DocTest constructor.
  572.  
  573.         If the optional argument `recurse` is false, then `find` will
  574.         only examine the given object, and not any contained objects.
  575.  
  576.         If the optional argument `exclude_empty` is false, then `find`
  577.         will include tests for objects with empty docstrings.
  578.         '''
  579.         self._parser = parser
  580.         self._verbose = verbose
  581.         self._recurse = recurse
  582.         self._exclude_empty = exclude_empty
  583.  
  584.     
  585.     def find(self, obj, name = None, module = None, globs = None, extraglobs = None):
  586.         """
  587.         Return a list of the DocTests that are defined by the given
  588.         object's docstring, or by any of its contained objects'
  589.         docstrings.
  590.  
  591.         The optional parameter `module` is the module that contains
  592.         the given object.  If the module is not specified or is None, then
  593.         the test finder will attempt to automatically determine the
  594.         correct module.  The object's module is used:
  595.  
  596.             - As a default namespace, if `globs` is not specified.
  597.             - To prevent the DocTestFinder from extracting DocTests
  598.               from objects that are imported from other modules.
  599.             - To find the name of the file containing the object.
  600.             - To help find the line number of the object within its
  601.               file.
  602.  
  603.         Contained objects whose module does not match `module` are ignored.
  604.  
  605.         If `module` is False, no attempt to find the module will be made.
  606.         This is obscure, of use mostly in tests:  if `module` is False, or
  607.         is None but cannot be found automatically, then all objects are
  608.         considered to belong to the (non-existent) module, so all contained
  609.         objects will (recursively) be searched for doctests.
  610.  
  611.         The globals for each DocTest is formed by combining `globs`
  612.         and `extraglobs` (bindings in `extraglobs` override bindings
  613.         in `globs`).  A new copy of the globals dictionary is created
  614.         for each DocTest.  If `globs` is not specified, then it
  615.         defaults to the module's `__dict__`, if specified, or {}
  616.         otherwise.  If `extraglobs` is not specified, then it defaults
  617.         to {}.
  618.  
  619.         """
  620.         if name is None:
  621.             name = getattr(obj, '__name__', None)
  622.             if name is None:
  623.                 raise ValueError("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))
  624.             
  625.         
  626.         if module is False:
  627.             module = None
  628.         elif module is None:
  629.             module = inspect.getmodule(obj)
  630.         
  631.         
  632.         try:
  633.             if not inspect.getsourcefile(obj):
  634.                 pass
  635.             file = inspect.getfile(obj)
  636.             source_lines = linecache.getlines(file)
  637.             if not source_lines:
  638.                 source_lines = None
  639.         except TypeError:
  640.             source_lines = None
  641.  
  642.         if globs is None:
  643.             if module is None:
  644.                 globs = { }
  645.             else:
  646.                 globs = module.__dict__.copy()
  647.         else:
  648.             globs = globs.copy()
  649.         if extraglobs is not None:
  650.             globs.update(extraglobs)
  651.         
  652.         tests = []
  653.         self._find(tests, obj, name, module, source_lines, globs, { })
  654.         tests.sort()
  655.         return tests
  656.  
  657.     
  658.     def _from_module(self, module, object):
  659.         '''
  660.         Return true if the given object is defined in the given
  661.         module.
  662.         '''
  663.         if module is None:
  664.             return True
  665.         elif inspect.isfunction(object):
  666.             return module.__dict__ is object.func_globals
  667.         elif inspect.isclass(object):
  668.             return module.__name__ == object.__module__
  669.         elif inspect.getmodule(object) is not None:
  670.             return module is inspect.getmodule(object)
  671.         elif hasattr(object, '__module__'):
  672.             return module.__name__ == object.__module__
  673.         elif isinstance(object, property):
  674.             return True
  675.         else:
  676.             raise ValueError('object must be a class or function')
  677.  
  678.     
  679.     def _find(self, tests, obj, name, module, source_lines, globs, seen):
  680.         '''
  681.         Find tests for the given object and any contained objects, and
  682.         add them to `tests`.
  683.         '''
  684.         if self._verbose:
  685.             print 'Finding tests in %s' % name
  686.         
  687.         if id(obj) in seen:
  688.             return None
  689.         
  690.         seen[id(obj)] = 1
  691.         test = self._get_test(obj, name, module, globs, source_lines)
  692.         if test is not None:
  693.             tests.append(test)
  694.         
  695.         if inspect.ismodule(obj) and self._recurse:
  696.             for valname, val in obj.__dict__.items():
  697.                 valname = '%s.%s' % (name, valname)
  698.                 if (inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val):
  699.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  700.                     continue
  701.             
  702.         
  703.         if inspect.ismodule(obj) and self._recurse:
  704.             for valname, val in getattr(obj, '__test__', { }).items():
  705.                 if not isinstance(valname, basestring):
  706.                     raise ValueError('DocTestFinder.find: __test__ keys must be strings: %r' % (type(valname),))
  707.                 
  708.                 if not inspect.isfunction(val) and inspect.isclass(val) and inspect.ismethod(val) and inspect.ismodule(val) or isinstance(val, basestring):
  709.                     raise ValueError('DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %r' % (type(val),))
  710.                 
  711.                 valname = '%s.__test__.%s' % (name, valname)
  712.                 self._find(tests, val, valname, module, source_lines, globs, seen)
  713.             
  714.         
  715.         if inspect.isclass(obj) and self._recurse:
  716.             for valname, val in obj.__dict__.items():
  717.                 if isinstance(val, staticmethod):
  718.                     val = getattr(obj, valname)
  719.                 
  720.                 if isinstance(val, classmethod):
  721.                     val = getattr(obj, valname).im_func
  722.                 
  723.                 if (inspect.isfunction(val) and inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val):
  724.                     valname = '%s.%s' % (name, valname)
  725.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  726.                     continue
  727.             
  728.         
  729.  
  730.     
  731.     def _get_test(self, obj, name, module, globs, source_lines):
  732.         '''
  733.         Return a DocTest for the given object, if it defines a docstring;
  734.         otherwise, return None.
  735.         '''
  736.         if isinstance(obj, basestring):
  737.             docstring = obj
  738.         else:
  739.             
  740.             try:
  741.                 if obj.__doc__ is None:
  742.                     docstring = ''
  743.                 else:
  744.                     docstring = obj.__doc__
  745.                     if not isinstance(docstring, basestring):
  746.                         docstring = str(docstring)
  747.             except (TypeError, AttributeError):
  748.                 docstring = ''
  749.             
  750.  
  751.         lineno = self._find_lineno(obj, source_lines)
  752.         if self._exclude_empty and not docstring:
  753.             return None
  754.         
  755.         if module is None:
  756.             filename = None
  757.         else:
  758.             filename = getattr(module, '__file__', module.__name__)
  759.             if filename[-4:] in ('.pyc', '.pyo'):
  760.                 filename = filename[:-1]
  761.             
  762.         return self._parser.get_doctest(docstring, globs, name, filename, lineno)
  763.  
  764.     
  765.     def _find_lineno(self, obj, source_lines):
  766.         """
  767.         Return a line number of the given object's docstring.  Note:
  768.         this method assumes that the object has a docstring.
  769.         """
  770.         lineno = None
  771.         if inspect.ismodule(obj):
  772.             lineno = 0
  773.         
  774.         if inspect.isclass(obj):
  775.             if source_lines is None:
  776.                 return None
  777.             
  778.             pat = re.compile('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))
  779.             for i, line in enumerate(source_lines):
  780.                 if pat.match(line):
  781.                     lineno = i
  782.                     break
  783.                     continue
  784.             
  785.         
  786.         if inspect.ismethod(obj):
  787.             obj = obj.im_func
  788.         
  789.         if inspect.isfunction(obj):
  790.             obj = obj.func_code
  791.         
  792.         if inspect.istraceback(obj):
  793.             obj = obj.tb_frame
  794.         
  795.         if inspect.isframe(obj):
  796.             obj = obj.f_code
  797.         
  798.         if inspect.iscode(obj):
  799.             lineno = getattr(obj, 'co_firstlineno', None) - 1
  800.         
  801.         if lineno is not None:
  802.             if source_lines is None:
  803.                 return lineno + 1
  804.             
  805.             pat = re.compile('(^|.*:)\\s*\\w*("|\')')
  806.             for lineno in range(lineno, len(source_lines)):
  807.                 if pat.match(source_lines[lineno]):
  808.                     return lineno
  809.                     continue
  810.             
  811.         
  812.         return None
  813.  
  814.  
  815.  
  816. class DocTestRunner:
  817.     """
  818.     A class used to run DocTest test cases, and accumulate statistics.
  819.     The `run` method is used to process a single DocTest case.  It
  820.     returns a tuple `(f, t)`, where `t` is the number of test cases
  821.     tried, and `f` is the number of test cases that failed.
  822.  
  823.         >>> tests = DocTestFinder().find(_TestClass)
  824.         >>> runner = DocTestRunner(verbose=False)
  825.         >>> tests.sort(key = lambda test: test.name)
  826.         >>> for test in tests:
  827.         ...     print test.name, '->', runner.run(test)
  828.         _TestClass -> (0, 2)
  829.         _TestClass.__init__ -> (0, 2)
  830.         _TestClass.get -> (0, 2)
  831.         _TestClass.square -> (0, 1)
  832.  
  833.     The `summarize` method prints a summary of all the test cases that
  834.     have been run by the runner, and returns an aggregated `(f, t)`
  835.     tuple:
  836.  
  837.         >>> runner.summarize(verbose=1)
  838.         4 items passed all tests:
  839.            2 tests in _TestClass
  840.            2 tests in _TestClass.__init__
  841.            2 tests in _TestClass.get
  842.            1 tests in _TestClass.square
  843.         7 tests in 4 items.
  844.         7 passed and 0 failed.
  845.         Test passed.
  846.         (0, 7)
  847.  
  848.     The aggregated number of tried examples and failed examples is
  849.     also available via the `tries` and `failures` attributes:
  850.  
  851.         >>> runner.tries
  852.         7
  853.         >>> runner.failures
  854.         0
  855.  
  856.     The comparison between expected outputs and actual outputs is done
  857.     by an `OutputChecker`.  This comparison may be customized with a
  858.     number of option flags; see the documentation for `testmod` for
  859.     more information.  If the option flags are insufficient, then the
  860.     comparison may also be customized by passing a subclass of
  861.     `OutputChecker` to the constructor.
  862.  
  863.     The test runner's display output can be controlled in two ways.
  864.     First, an output function (`out) can be passed to
  865.     `TestRunner.run`; this function will be called with strings that
  866.     should be displayed.  It defaults to `sys.stdout.write`.  If
  867.     capturing the output is not sufficient, then the display output
  868.     can be also customized by subclassing DocTestRunner, and
  869.     overriding the methods `report_start`, `report_success`,
  870.     `report_unexpected_exception`, and `report_failure`.
  871.     """
  872.     DIVIDER = '*' * 70
  873.     
  874.     def __init__(self, checker = None, verbose = None, optionflags = 0):
  875.         """
  876.         Create a new test runner.
  877.  
  878.         Optional keyword arg `checker` is the `OutputChecker` that
  879.         should be used to compare the expected outputs and actual
  880.         outputs of doctest examples.
  881.  
  882.         Optional keyword arg 'verbose' prints lots of stuff if true,
  883.         only failures if false; by default, it's true iff '-v' is in
  884.         sys.argv.
  885.  
  886.         Optional argument `optionflags` can be used to control how the
  887.         test runner compares expected output to actual output, and how
  888.         it displays failures.  See the documentation for `testmod` for
  889.         more information.
  890.         """
  891.         if not checker:
  892.             pass
  893.         self._checker = OutputChecker()
  894.         if verbose is None:
  895.             verbose = '-v' in sys.argv
  896.         
  897.         self._verbose = verbose
  898.         self.optionflags = optionflags
  899.         self.original_optionflags = optionflags
  900.         self.tries = 0
  901.         self.failures = 0
  902.         self._name2ft = { }
  903.         self._fakeout = _SpoofOut()
  904.  
  905.     
  906.     def report_start(self, out, test, example):
  907.         '''
  908.         Report that the test runner is about to process the given
  909.         example.  (Only displays a message if verbose=True)
  910.         '''
  911.         if self._verbose:
  912.             if example.want:
  913.                 out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want))
  914.             else:
  915.                 out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n')
  916.         
  917.  
  918.     
  919.     def report_success(self, out, test, example, got):
  920.         '''
  921.         Report that the given example ran successfully.  (Only
  922.         displays a message if verbose=True)
  923.         '''
  924.         if self._verbose:
  925.             out('ok\n')
  926.         
  927.  
  928.     
  929.     def report_failure(self, out, test, example, got):
  930.         '''
  931.         Report that the given example failed.
  932.         '''
  933.         out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags))
  934.  
  935.     
  936.     def report_unexpected_exception(self, out, test, example, exc_info):
  937.         '''
  938.         Report that the given example raised an unexpected exception.
  939.         '''
  940.         out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  941.  
  942.     
  943.     def _failure_header(self, test, example):
  944.         out = [
  945.             self.DIVIDER]
  946.         if test.filename:
  947.             if test.lineno is not None and example.lineno is not None:
  948.                 lineno = test.lineno + example.lineno + 1
  949.             else:
  950.                 lineno = '?'
  951.             out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name))
  952.         else:
  953.             out.append('Line %s, in %s' % (example.lineno + 1, test.name))
  954.         out.append('Failed example:')
  955.         source = example.source
  956.         out.append(_indent(source))
  957.         return '\n'.join(out)
  958.  
  959.     
  960.     def __run(self, test, compileflags, out):
  961.         '''
  962.         Run the examples in `test`.  Write the outcome of each example
  963.         with one of the `DocTestRunner.report_*` methods, using the
  964.         writer function `out`.  `compileflags` is the set of compiler
  965.         flags that should be used to execute examples.  Return a tuple
  966.         `(f, t)`, where `t` is the number of examples tried, and `f`
  967.         is the number of examples that failed.  The examples are run
  968.         in the namespace `test.globs`.
  969.         '''
  970.         failures = tries = 0
  971.         original_optionflags = self.optionflags
  972.         (SUCCESS, FAILURE, BOOM) = range(3)
  973.         check = self._checker.check_output
  974.         for examplenum, example in enumerate(test.examples):
  975.             if self.optionflags & REPORT_ONLY_FIRST_FAILURE:
  976.                 pass
  977.             quiet = failures > 0
  978.             self.optionflags = original_optionflags
  979.             if example.options:
  980.                 for optionflag, val in example.options.items():
  981.                     if val:
  982.                         self.optionflags |= optionflag
  983.                         continue
  984.                     self
  985.                     self.optionflags &= ~optionflag
  986.                 
  987.             
  988.             if self.optionflags & SKIP:
  989.                 continue
  990.             
  991.             tries += 1
  992.             if not quiet:
  993.                 self.report_start(out, test, example)
  994.             
  995.             filename = '<doctest %s[%d]>' % (test.name, examplenum)
  996.             
  997.             try:
  998.                 exec compile(example.source, filename, 'single', compileflags, 1) in test.globs
  999.                 self.debugger.set_continue()
  1000.                 exception = None
  1001.             except KeyboardInterrupt:
  1002.                 raise 
  1003.             except:
  1004.                 exception = sys.exc_info()
  1005.                 self.debugger.set_continue()
  1006.  
  1007.             got = self._fakeout.getvalue()
  1008.             self._fakeout.truncate(0)
  1009.             outcome = FAILURE
  1010.             if exception is None:
  1011.                 if check(example.want, got, self.optionflags):
  1012.                     outcome = SUCCESS
  1013.                 
  1014.             else:
  1015.                 exc_info = sys.exc_info()
  1016.                 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1017.                 if not quiet:
  1018.                     got += _exception_traceback(exc_info)
  1019.                 
  1020.                 if example.exc_msg is None:
  1021.                     outcome = BOOM
  1022.                 elif check(example.exc_msg, exc_msg, self.optionflags):
  1023.                     outcome = SUCCESS
  1024.                 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1025.                     m1 = re.match('[^:]*:', example.exc_msg)
  1026.                     m2 = re.match('[^:]*:', exc_msg)
  1027.                     if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags):
  1028.                         outcome = SUCCESS
  1029.                     
  1030.                 
  1031.             if outcome is SUCCESS:
  1032.                 if not quiet:
  1033.                     self.report_success(out, test, example, got)
  1034.                 
  1035.             quiet
  1036.             if outcome is FAILURE:
  1037.                 if not quiet:
  1038.                     self.report_failure(out, test, example, got)
  1039.                 
  1040.                 failures += 1
  1041.                 continue
  1042.             if outcome is BOOM:
  1043.                 if not quiet:
  1044.                     self.report_unexpected_exception(out, test, example, exc_info)
  1045.                 
  1046.                 failures += 1
  1047.                 continue
  1048.             if not False:
  1049.                 raise AssertionError, ('unknown outcome', outcome)
  1050.         
  1051.         self.optionflags = original_optionflags
  1052.         self._DocTestRunner__record_outcome(test, failures, tries)
  1053.         return (failures, tries)
  1054.  
  1055.     
  1056.     def __record_outcome(self, test, f, t):
  1057.         '''
  1058.         Record the fact that the given DocTest (`test`) generated `f`
  1059.         failures out of `t` tried examples.
  1060.         '''
  1061.         (f2, t2) = self._name2ft.get(test.name, (0, 0))
  1062.         self._name2ft[test.name] = (f + f2, t + t2)
  1063.         self.failures += f
  1064.         self.tries += t
  1065.  
  1066.     __LINECACHE_FILENAME_RE = re.compile('<doctest (?P<name>[\\w\\.]+)\\[(?P<examplenum>\\d+)\\]>$')
  1067.     
  1068.     def __patched_linecache_getlines(self, filename, module_globals = None):
  1069.         m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename)
  1070.         if m and m.group('name') == self.test.name:
  1071.             example = self.test.examples[int(m.group('examplenum'))]
  1072.             return example.source.splitlines(True)
  1073.         else:
  1074.             return self.save_linecache_getlines(filename, module_globals)
  1075.  
  1076.     
  1077.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1078.         '''
  1079.         Run the examples in `test`, and display the results using the
  1080.         writer function `out`.
  1081.  
  1082.         The examples are run in the namespace `test.globs`.  If
  1083.         `clear_globs` is true (the default), then this namespace will
  1084.         be cleared after the test runs, to help with garbage
  1085.         collection.  If you would like to examine the namespace after
  1086.         the test completes, then use `clear_globs=False`.
  1087.  
  1088.         `compileflags` gives the set of flags that should be used by
  1089.         the Python compiler when running the examples.  If not
  1090.         specified, then it will default to the set of future-import
  1091.         flags that apply to `globs`.
  1092.  
  1093.         The output of each example is checked using
  1094.         `DocTestRunner.check_output`, and the results are formatted by
  1095.         the `DocTestRunner.report_*` methods.
  1096.         '''
  1097.         self.test = test
  1098.         if compileflags is None:
  1099.             compileflags = _extract_future_flags(test.globs)
  1100.         
  1101.         save_stdout = sys.stdout
  1102.         if out is None:
  1103.             out = save_stdout.write
  1104.         
  1105.         sys.stdout = self._fakeout
  1106.         save_set_trace = pdb.set_trace
  1107.         self.debugger = _OutputRedirectingPdb(save_stdout)
  1108.         self.debugger.reset()
  1109.         pdb.set_trace = self.debugger.set_trace
  1110.         self.save_linecache_getlines = linecache.getlines
  1111.         linecache.getlines = self._DocTestRunner__patched_linecache_getlines
  1112.         
  1113.         try:
  1114.             return self._DocTestRunner__run(test, compileflags, out)
  1115.         finally:
  1116.             sys.stdout = save_stdout
  1117.             pdb.set_trace = save_set_trace
  1118.             linecache.getlines = self.save_linecache_getlines
  1119.             if clear_globs:
  1120.                 test.globs.clear()
  1121.             
  1122.  
  1123.  
  1124.     
  1125.     def summarize(self, verbose = None):
  1126.         """
  1127.         Print a summary of all the test cases that have been run by
  1128.         this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1129.         the total number of failed examples, and `t` is the total
  1130.         number of tried examples.
  1131.  
  1132.         The optional `verbose` argument controls how detailed the
  1133.         summary is.  If the verbosity is not specified, then the
  1134.         DocTestRunner's verbosity is used.
  1135.         """
  1136.         if verbose is None:
  1137.             verbose = self._verbose
  1138.         
  1139.         notests = []
  1140.         passed = []
  1141.         failed = []
  1142.         totalt = totalf = 0
  1143.         for x in self._name2ft.items():
  1144.             (f, t) = (name,)
  1145.             if not f <= t:
  1146.                 raise AssertionError
  1147.             x
  1148.             totalt += t
  1149.             totalf += f
  1150.             if t == 0:
  1151.                 notests.append(name)
  1152.                 continue
  1153.             if f == 0:
  1154.                 passed.append((name, t))
  1155.                 continue
  1156.             failed.append(x)
  1157.         
  1158.         if verbose:
  1159.             if notests:
  1160.                 print len(notests), 'items had no tests:'
  1161.                 notests.sort()
  1162.                 for thing in notests:
  1163.                     print '   ', thing
  1164.                 
  1165.             
  1166.             if passed:
  1167.                 print len(passed), 'items passed all tests:'
  1168.                 passed.sort()
  1169.                 for thing, count in passed:
  1170.                     print ' %3d tests in %s' % (count, thing)
  1171.                 
  1172.             
  1173.         
  1174.         if failed:
  1175.             print self.DIVIDER
  1176.             print len(failed), 'items had failures:'
  1177.             failed.sort()
  1178.             for f, t in failed:
  1179.                 print ' %3d of %3d in %s' % (f, t, thing)
  1180.             
  1181.         
  1182.         if verbose:
  1183.             print totalt, 'tests in', len(self._name2ft), 'items.'
  1184.             print totalt - totalf, 'passed and', totalf, 'failed.'
  1185.         
  1186.         if totalf:
  1187.             print '***Test Failed***', totalf, 'failures.'
  1188.         elif verbose:
  1189.             print 'Test passed.'
  1190.         
  1191.         return (totalf, totalt)
  1192.  
  1193.     
  1194.     def merge(self, other):
  1195.         d = self._name2ft
  1196.         for f, t in other._name2ft.items():
  1197.             d[name] = (f, t)
  1198.         
  1199.  
  1200.  
  1201.  
  1202. class OutputChecker:
  1203.     '''
  1204.     A class used to check the whether the actual output from a doctest
  1205.     example matches the expected output.  `OutputChecker` defines two
  1206.     methods: `check_output`, which compares a given pair of outputs,
  1207.     and returns true if they match; and `output_difference`, which
  1208.     returns a string describing the differences between two outputs.
  1209.     '''
  1210.     
  1211.     def check_output(self, want, got, optionflags):
  1212.         '''
  1213.         Return True iff the actual output from an example (`got`)
  1214.         matches the expected output (`want`).  These strings are
  1215.         always considered to match if they are identical; but
  1216.         depending on what option flags the test runner is using,
  1217.         several non-exact match types are also possible.  See the
  1218.         documentation for `TestRunner` for more information about
  1219.         option flags.
  1220.         '''
  1221.         if got == want:
  1222.             return True
  1223.         
  1224.         if not optionflags & DONT_ACCEPT_TRUE_FOR_1:
  1225.             if (got, want) == ('True\n', '1\n'):
  1226.                 return True
  1227.             
  1228.             if (got, want) == ('False\n', '0\n'):
  1229.                 return True
  1230.             
  1231.         
  1232.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  1233.             want = re.sub('(?m)^%s\\s*?$' % re.escape(BLANKLINE_MARKER), '', want)
  1234.             got = re.sub('(?m)^\\s*?$', '', got)
  1235.             if got == want:
  1236.                 return True
  1237.             
  1238.         
  1239.         if optionflags & NORMALIZE_WHITESPACE:
  1240.             got = ' '.join(got.split())
  1241.             want = ' '.join(want.split())
  1242.             if got == want:
  1243.                 return True
  1244.             
  1245.         
  1246.         if optionflags & ELLIPSIS:
  1247.             if _ellipsis_match(want, got):
  1248.                 return True
  1249.             
  1250.         
  1251.         return False
  1252.  
  1253.     
  1254.     def _do_a_fancy_diff(self, want, got, optionflags):
  1255.         if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF):
  1256.             return False
  1257.         
  1258.         if optionflags & REPORT_NDIFF:
  1259.             return True
  1260.         
  1261.         if want.count('\n') > 2:
  1262.             pass
  1263.         return got.count('\n') > 2
  1264.  
  1265.     
  1266.     def output_difference(self, example, got, optionflags):
  1267.         '''
  1268.         Return a string describing the differences between the
  1269.         expected output for a given example (`example`) and the actual
  1270.         output (`got`).  `optionflags` is the set of option flags used
  1271.         to compare `want` and `got`.
  1272.         '''
  1273.         want = example.want
  1274.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  1275.             got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1276.         
  1277.         if want and got:
  1278.             return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1279.         elif want:
  1280.             return 'Expected:\n%sGot nothing\n' % _indent(want)
  1281.         elif got:
  1282.             return 'Expected nothing\nGot:\n%s' % _indent(got)
  1283.         else:
  1284.             return 'Expected nothing\nGot nothing\n'
  1285.  
  1286.  
  1287.  
  1288. class DocTestFailure(Exception):
  1289.     '''A DocTest example has failed in debugging mode.
  1290.  
  1291.     The exception instance has variables:
  1292.  
  1293.     - test: the DocTest object being run
  1294.  
  1295.     - example: the Example object that failed
  1296.  
  1297.     - got: the actual output
  1298.     '''
  1299.     
  1300.     def __init__(self, test, example, got):
  1301.         self.test = test
  1302.         self.example = example
  1303.         self.got = got
  1304.  
  1305.     
  1306.     def __str__(self):
  1307.         return str(self.test)
  1308.  
  1309.  
  1310.  
  1311. class UnexpectedException(Exception):
  1312.     '''A DocTest example has encountered an unexpected exception
  1313.  
  1314.     The exception instance has variables:
  1315.  
  1316.     - test: the DocTest object being run
  1317.  
  1318.     - example: the Example object that failed
  1319.  
  1320.     - exc_info: the exception info
  1321.     '''
  1322.     
  1323.     def __init__(self, test, example, exc_info):
  1324.         self.test = test
  1325.         self.example = example
  1326.         self.exc_info = exc_info
  1327.  
  1328.     
  1329.     def __str__(self):
  1330.         return str(self.test)
  1331.  
  1332.  
  1333.  
  1334. class DebugRunner(DocTestRunner):
  1335.     """Run doc tests but raise an exception as soon as there is a failure.
  1336.  
  1337.        If an unexpected exception occurs, an UnexpectedException is raised.
  1338.        It contains the test, the example, and the original exception:
  1339.  
  1340.          >>> runner = DebugRunner(verbose=False)
  1341.          >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1342.          ...                                    {}, 'foo', 'foo.py', 0)
  1343.          >>> try:
  1344.          ...     runner.run(test)
  1345.          ... except UnexpectedException, failure:
  1346.          ...     pass
  1347.  
  1348.          >>> failure.test is test
  1349.          True
  1350.  
  1351.          >>> failure.example.want
  1352.          '42\\n'
  1353.  
  1354.          >>> exc_info = failure.exc_info
  1355.          >>> raise exc_info[0], exc_info[1], exc_info[2]
  1356.          Traceback (most recent call last):
  1357.          ...
  1358.          KeyError
  1359.  
  1360.        We wrap the original exception to give the calling application
  1361.        access to the test and example information.
  1362.  
  1363.        If the output doesn't match, then a DocTestFailure is raised:
  1364.  
  1365.          >>> test = DocTestParser().get_doctest('''
  1366.          ...      >>> x = 1
  1367.          ...      >>> x
  1368.          ...      2
  1369.          ...      ''', {}, 'foo', 'foo.py', 0)
  1370.  
  1371.          >>> try:
  1372.          ...    runner.run(test)
  1373.          ... except DocTestFailure, failure:
  1374.          ...    pass
  1375.  
  1376.        DocTestFailure objects provide access to the test:
  1377.  
  1378.          >>> failure.test is test
  1379.          True
  1380.  
  1381.        As well as to the example:
  1382.  
  1383.          >>> failure.example.want
  1384.          '2\\n'
  1385.  
  1386.        and the actual output:
  1387.  
  1388.          >>> failure.got
  1389.          '1\\n'
  1390.  
  1391.        If a failure or error occurs, the globals are left intact:
  1392.  
  1393.          >>> del test.globs['__builtins__']
  1394.          >>> test.globs
  1395.          {'x': 1}
  1396.  
  1397.          >>> test = DocTestParser().get_doctest('''
  1398.          ...      >>> x = 2
  1399.          ...      >>> raise KeyError
  1400.          ...      ''', {}, 'foo', 'foo.py', 0)
  1401.  
  1402.          >>> runner.run(test)
  1403.          Traceback (most recent call last):
  1404.          ...
  1405.          UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1406.  
  1407.          >>> del test.globs['__builtins__']
  1408.          >>> test.globs
  1409.          {'x': 2}
  1410.  
  1411.        But the globals are cleared if there is no error:
  1412.  
  1413.          >>> test = DocTestParser().get_doctest('''
  1414.          ...      >>> x = 2
  1415.          ...      ''', {}, 'foo', 'foo.py', 0)
  1416.  
  1417.          >>> runner.run(test)
  1418.          (0, 1)
  1419.  
  1420.          >>> test.globs
  1421.          {}
  1422.  
  1423.        """
  1424.     
  1425.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1426.         r = DocTestRunner.run(self, test, compileflags, out, False)
  1427.         if clear_globs:
  1428.             test.globs.clear()
  1429.         
  1430.         return r
  1431.  
  1432.     
  1433.     def report_unexpected_exception(self, out, test, example, exc_info):
  1434.         raise UnexpectedException(test, example, exc_info)
  1435.  
  1436.     
  1437.     def report_failure(self, out, test, example, got):
  1438.         raise DocTestFailure(test, example, got)
  1439.  
  1440.  
  1441. master = None
  1442.  
  1443. def testmod(m = None, name = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, exclude_empty = False):
  1444.     '''m=None, name=None, globs=None, verbose=None, report=True,
  1445.        optionflags=0, extraglobs=None, raise_on_error=False,
  1446.        exclude_empty=False
  1447.  
  1448.     Test examples in docstrings in functions and classes reachable
  1449.     from module m (or the current module if m is not supplied), starting
  1450.     with m.__doc__.
  1451.  
  1452.     Also test examples reachable from dict m.__test__ if it exists and is
  1453.     not None.  m.__test__ maps names to functions, classes and strings;
  1454.     function and class docstrings are tested even if the name is private;
  1455.     strings are tested directly, as if they were docstrings.
  1456.  
  1457.     Return (#failures, #tests).
  1458.  
  1459.     See doctest.__doc__ for an overview.
  1460.  
  1461.     Optional keyword arg "name" gives the name of the module; by default
  1462.     use m.__name__.
  1463.  
  1464.     Optional keyword arg "globs" gives a dict to be used as the globals
  1465.     when executing examples; by default, use m.__dict__.  A copy of this
  1466.     dict is actually used for each docstring, so that each docstring\'s
  1467.     examples start with a clean slate.
  1468.  
  1469.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1470.     merged into the globals that are used to execute examples.  By
  1471.     default, no extra globals are used.  This is new in 2.4.
  1472.  
  1473.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1474.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1475.  
  1476.     Optional keyword arg "report" prints a summary at the end when true,
  1477.     else prints nothing at the end.  In verbose mode, the summary is
  1478.     detailed, else very brief (in fact, empty if all tests passed).
  1479.  
  1480.     Optional keyword arg "optionflags" or\'s together module constants,
  1481.     and defaults to 0.  This is new in 2.3.  Possible values (see the
  1482.     docs for details):
  1483.  
  1484.         DONT_ACCEPT_TRUE_FOR_1
  1485.         DONT_ACCEPT_BLANKLINE
  1486.         NORMALIZE_WHITESPACE
  1487.         ELLIPSIS
  1488.         SKIP
  1489.         IGNORE_EXCEPTION_DETAIL
  1490.         REPORT_UDIFF
  1491.         REPORT_CDIFF
  1492.         REPORT_NDIFF
  1493.         REPORT_ONLY_FIRST_FAILURE
  1494.  
  1495.     Optional keyword arg "raise_on_error" raises an exception on the
  1496.     first unexpected exception or failure. This allows failures to be
  1497.     post-mortem debugged.
  1498.  
  1499.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1500.     class doctest.Tester, then merges the results into (or creates)
  1501.     global Tester instance doctest.master.  Methods of doctest.master
  1502.     can be called directly too, if you want to do something unusual.
  1503.     Passing report=0 to testmod is especially useful then, to delay
  1504.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1505.     when you\'re done fiddling.
  1506.     '''
  1507.     global master
  1508.     if m is None:
  1509.         m = sys.modules.get('__main__')
  1510.     
  1511.     if not inspect.ismodule(m):
  1512.         raise TypeError('testmod: module required; %r' % (m,))
  1513.     
  1514.     if name is None:
  1515.         name = m.__name__
  1516.     
  1517.     finder = DocTestFinder(exclude_empty = exclude_empty)
  1518.     if raise_on_error:
  1519.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1520.     else:
  1521.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1522.     for test in finder.find(m, name, globs = globs, extraglobs = extraglobs):
  1523.         runner.run(test)
  1524.     
  1525.     if report:
  1526.         runner.summarize()
  1527.     
  1528.     if master is None:
  1529.         master = runner
  1530.     else:
  1531.         master.merge(runner)
  1532.     return (runner.failures, runner.tries)
  1533.  
  1534.  
  1535. def testfile(filename, module_relative = True, name = None, package = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, parser = DocTestParser(), encoding = None):
  1536.     '''
  1537.     Test examples in the given file.  Return (#failures, #tests).
  1538.  
  1539.     Optional keyword arg "module_relative" specifies how filenames
  1540.     should be interpreted:
  1541.  
  1542.       - If "module_relative" is True (the default), then "filename"
  1543.          specifies a module-relative path.  By default, this path is
  1544.          relative to the calling module\'s directory; but if the
  1545.          "package" argument is specified, then it is relative to that
  1546.          package.  To ensure os-independence, "filename" should use
  1547.          "/" characters to separate path segments, and should not
  1548.          be an absolute path (i.e., it may not begin with "/").
  1549.  
  1550.       - If "module_relative" is False, then "filename" specifies an
  1551.         os-specific path.  The path may be absolute or relative (to
  1552.         the current working directory).
  1553.  
  1554.     Optional keyword arg "name" gives the name of the test; by default
  1555.     use the file\'s basename.
  1556.  
  1557.     Optional keyword argument "package" is a Python package or the
  1558.     name of a Python package whose directory should be used as the
  1559.     base directory for a module relative filename.  If no package is
  1560.     specified, then the calling module\'s directory is used as the base
  1561.     directory for module relative filenames.  It is an error to
  1562.     specify "package" if "module_relative" is False.
  1563.  
  1564.     Optional keyword arg "globs" gives a dict to be used as the globals
  1565.     when executing examples; by default, use {}.  A copy of this dict
  1566.     is actually used for each docstring, so that each docstring\'s
  1567.     examples start with a clean slate.
  1568.  
  1569.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1570.     merged into the globals that are used to execute examples.  By
  1571.     default, no extra globals are used.
  1572.  
  1573.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1574.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1575.  
  1576.     Optional keyword arg "report" prints a summary at the end when true,
  1577.     else prints nothing at the end.  In verbose mode, the summary is
  1578.     detailed, else very brief (in fact, empty if all tests passed).
  1579.  
  1580.     Optional keyword arg "optionflags" or\'s together module constants,
  1581.     and defaults to 0.  Possible values (see the docs for details):
  1582.  
  1583.         DONT_ACCEPT_TRUE_FOR_1
  1584.         DONT_ACCEPT_BLANKLINE
  1585.         NORMALIZE_WHITESPACE
  1586.         ELLIPSIS
  1587.         SKIP
  1588.         IGNORE_EXCEPTION_DETAIL
  1589.         REPORT_UDIFF
  1590.         REPORT_CDIFF
  1591.         REPORT_NDIFF
  1592.         REPORT_ONLY_FIRST_FAILURE
  1593.  
  1594.     Optional keyword arg "raise_on_error" raises an exception on the
  1595.     first unexpected exception or failure. This allows failures to be
  1596.     post-mortem debugged.
  1597.  
  1598.     Optional keyword arg "parser" specifies a DocTestParser (or
  1599.     subclass) that should be used to extract tests from the files.
  1600.  
  1601.     Optional keyword arg "encoding" specifies an encoding that should
  1602.     be used to convert the file to unicode.
  1603.  
  1604.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1605.     class doctest.Tester, then merges the results into (or creates)
  1606.     global Tester instance doctest.master.  Methods of doctest.master
  1607.     can be called directly too, if you want to do something unusual.
  1608.     Passing report=0 to testmod is especially useful then, to delay
  1609.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1610.     when you\'re done fiddling.
  1611.     '''
  1612.     global master
  1613.     if package and not module_relative:
  1614.         raise ValueError('Package may only be specified for module-relative paths.')
  1615.     
  1616.     (text, filename) = _load_testfile(filename, package, module_relative)
  1617.     if name is None:
  1618.         name = os.path.basename(filename)
  1619.     
  1620.     if globs is None:
  1621.         globs = { }
  1622.     else:
  1623.         globs = globs.copy()
  1624.     if extraglobs is not None:
  1625.         globs.update(extraglobs)
  1626.     
  1627.     if raise_on_error:
  1628.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1629.     else:
  1630.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1631.     if encoding is not None:
  1632.         text = text.decode(encoding)
  1633.     
  1634.     test = parser.get_doctest(text, globs, name, filename, 0)
  1635.     runner.run(test)
  1636.     if report:
  1637.         runner.summarize()
  1638.     
  1639.     if master is None:
  1640.         master = runner
  1641.     else:
  1642.         master.merge(runner)
  1643.     return (runner.failures, runner.tries)
  1644.  
  1645.  
  1646. def run_docstring_examples(f, globs, verbose = False, name = 'NoName', compileflags = None, optionflags = 0):
  1647.     """
  1648.     Test examples in the given object's docstring (`f`), using `globs`
  1649.     as globals.  Optional argument `name` is used in failure messages.
  1650.     If the optional argument `verbose` is true, then generate output
  1651.     even if there are no failures.
  1652.  
  1653.     `compileflags` gives the set of flags that should be used by the
  1654.     Python compiler when running the examples.  If not specified, then
  1655.     it will default to the set of future-import flags that apply to
  1656.     `globs`.
  1657.  
  1658.     Optional keyword arg `optionflags` specifies options for the
  1659.     testing and output.  See the documentation for `testmod` for more
  1660.     information.
  1661.     """
  1662.     finder = DocTestFinder(verbose = verbose, recurse = False)
  1663.     runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1664.     for test in finder.find(f, name, globs = globs):
  1665.         runner.run(test, compileflags = compileflags)
  1666.     
  1667.  
  1668.  
  1669. class Tester:
  1670.     
  1671.     def __init__(self, mod = None, globs = None, verbose = None, optionflags = 0):
  1672.         warnings.warn('class Tester is deprecated; use class doctest.DocTestRunner instead', DeprecationWarning, stacklevel = 2)
  1673.         if mod is None and globs is None:
  1674.             raise TypeError('Tester.__init__: must specify mod or globs')
  1675.         
  1676.         if mod is not None and not inspect.ismodule(mod):
  1677.             raise TypeError('Tester.__init__: mod must be a module; %r' % (mod,))
  1678.         
  1679.         if globs is None:
  1680.             globs = mod.__dict__
  1681.         
  1682.         self.globs = globs
  1683.         self.verbose = verbose
  1684.         self.optionflags = optionflags
  1685.         self.testfinder = DocTestFinder()
  1686.         self.testrunner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1687.  
  1688.     
  1689.     def runstring(self, s, name):
  1690.         test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1691.         if self.verbose:
  1692.             print 'Running string', name
  1693.         
  1694.         (f, t) = self.testrunner.run(test)
  1695.         if self.verbose:
  1696.             print f, 'of', t, 'examples failed in string', name
  1697.         
  1698.         return (f, t)
  1699.  
  1700.     
  1701.     def rundoc(self, object, name = None, module = None):
  1702.         f = t = 0
  1703.         tests = self.testfinder.find(object, name, module = module, globs = self.globs)
  1704.         for test in tests:
  1705.             (f2, t2) = self.testrunner.run(test)
  1706.             f = f + f2
  1707.             t = t + t2
  1708.         
  1709.         return (f, t)
  1710.  
  1711.     
  1712.     def rundict(self, d, name, module = None):
  1713.         import new
  1714.         m = new.module(name)
  1715.         m.__dict__.update(d)
  1716.         if module is None:
  1717.             module = False
  1718.         
  1719.         return self.rundoc(m, name, module)
  1720.  
  1721.     
  1722.     def run__test__(self, d, name):
  1723.         import new
  1724.         m = new.module(name)
  1725.         m.__test__ = d
  1726.         return self.rundoc(m, name)
  1727.  
  1728.     
  1729.     def summarize(self, verbose = None):
  1730.         return self.testrunner.summarize(verbose)
  1731.  
  1732.     
  1733.     def merge(self, other):
  1734.         self.testrunner.merge(other.testrunner)
  1735.  
  1736.  
  1737. _unittest_reportflags = 0
  1738.  
  1739. def set_unittest_reportflags(flags):
  1740.     """Sets the unittest option flags.
  1741.  
  1742.     The old flag is returned so that a runner could restore the old
  1743.     value if it wished to:
  1744.  
  1745.       >>> import doctest
  1746.       >>> old = doctest._unittest_reportflags
  1747.       >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1748.       ...                          REPORT_ONLY_FIRST_FAILURE) == old
  1749.       True
  1750.  
  1751.       >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1752.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1753.       True
  1754.  
  1755.     Only reporting flags can be set:
  1756.  
  1757.       >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1758.       Traceback (most recent call last):
  1759.       ...
  1760.       ValueError: ('Only reporting flags allowed', 8)
  1761.  
  1762.       >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1763.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1764.       True
  1765.     """
  1766.     global _unittest_reportflags
  1767.     if flags & REPORTING_FLAGS != flags:
  1768.         raise ValueError('Only reporting flags allowed', flags)
  1769.     
  1770.     old = _unittest_reportflags
  1771.     _unittest_reportflags = flags
  1772.     return old
  1773.  
  1774.  
  1775. class DocTestCase(unittest.TestCase):
  1776.     
  1777.     def __init__(self, test, optionflags = 0, setUp = None, tearDown = None, checker = None):
  1778.         unittest.TestCase.__init__(self)
  1779.         self._dt_optionflags = optionflags
  1780.         self._dt_checker = checker
  1781.         self._dt_test = test
  1782.         self._dt_setUp = setUp
  1783.         self._dt_tearDown = tearDown
  1784.  
  1785.     
  1786.     def setUp(self):
  1787.         test = self._dt_test
  1788.         if self._dt_setUp is not None:
  1789.             self._dt_setUp(test)
  1790.         
  1791.  
  1792.     
  1793.     def tearDown(self):
  1794.         test = self._dt_test
  1795.         if self._dt_tearDown is not None:
  1796.             self._dt_tearDown(test)
  1797.         
  1798.         test.globs.clear()
  1799.  
  1800.     
  1801.     def runTest(self):
  1802.         test = self._dt_test
  1803.         old = sys.stdout
  1804.         new = StringIO()
  1805.         optionflags = self._dt_optionflags
  1806.         if not optionflags & REPORTING_FLAGS:
  1807.             optionflags |= _unittest_reportflags
  1808.         
  1809.         runner = DocTestRunner(optionflags = optionflags, checker = self._dt_checker, verbose = False)
  1810.         
  1811.         try:
  1812.             runner.DIVIDER = '-' * 70
  1813.             (failures, tries) = runner.run(test, out = new.write, clear_globs = False)
  1814.         finally:
  1815.             sys.stdout = old
  1816.  
  1817.         if failures:
  1818.             raise self.failureException(self.format_failure(new.getvalue()))
  1819.         
  1820.  
  1821.     
  1822.     def format_failure(self, err):
  1823.         test = self._dt_test
  1824.         if test.lineno is None:
  1825.             lineno = 'unknown line number'
  1826.         else:
  1827.             lineno = '%s' % test.lineno
  1828.         lname = '.'.join(test.name.split('.')[-1:])
  1829.         return 'Failed doctest test for %s\n  File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err)
  1830.  
  1831.     
  1832.     def debug(self):
  1833.         """Run the test case without results and without catching exceptions
  1834.  
  1835.            The unit test framework includes a debug method on test cases
  1836.            and test suites to support post-mortem debugging.  The test code
  1837.            is run in such a way that errors are not caught.  This way a
  1838.            caller can catch the errors and initiate post-mortem debugging.
  1839.  
  1840.            The DocTestCase provides a debug method that raises
  1841.            UnexpectedException errors if there is an unexepcted
  1842.            exception:
  1843.  
  1844.              >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1845.              ...                {}, 'foo', 'foo.py', 0)
  1846.              >>> case = DocTestCase(test)
  1847.              >>> try:
  1848.              ...     case.debug()
  1849.              ... except UnexpectedException, failure:
  1850.              ...     pass
  1851.  
  1852.            The UnexpectedException contains the test, the example, and
  1853.            the original exception:
  1854.  
  1855.              >>> failure.test is test
  1856.              True
  1857.  
  1858.              >>> failure.example.want
  1859.              '42\\n'
  1860.  
  1861.              >>> exc_info = failure.exc_info
  1862.              >>> raise exc_info[0], exc_info[1], exc_info[2]
  1863.              Traceback (most recent call last):
  1864.              ...
  1865.              KeyError
  1866.  
  1867.            If the output doesn't match, then a DocTestFailure is raised:
  1868.  
  1869.              >>> test = DocTestParser().get_doctest('''
  1870.              ...      >>> x = 1
  1871.              ...      >>> x
  1872.              ...      2
  1873.              ...      ''', {}, 'foo', 'foo.py', 0)
  1874.              >>> case = DocTestCase(test)
  1875.  
  1876.              >>> try:
  1877.              ...    case.debug()
  1878.              ... except DocTestFailure, failure:
  1879.              ...    pass
  1880.  
  1881.            DocTestFailure objects provide access to the test:
  1882.  
  1883.              >>> failure.test is test
  1884.              True
  1885.  
  1886.            As well as to the example:
  1887.  
  1888.              >>> failure.example.want
  1889.              '2\\n'
  1890.  
  1891.            and the actual output:
  1892.  
  1893.              >>> failure.got
  1894.              '1\\n'
  1895.  
  1896.            """
  1897.         self.setUp()
  1898.         runner = DebugRunner(optionflags = self._dt_optionflags, checker = self._dt_checker, verbose = False)
  1899.         runner.run(self._dt_test)
  1900.         self.tearDown()
  1901.  
  1902.     
  1903.     def id(self):
  1904.         return self._dt_test.name
  1905.  
  1906.     
  1907.     def __repr__(self):
  1908.         name = self._dt_test.name.split('.')
  1909.         return '%s (%s)' % (name[-1], '.'.join(name[:-1]))
  1910.  
  1911.     __str__ = __repr__
  1912.     
  1913.     def shortDescription(self):
  1914.         return 'Doctest: ' + self._dt_test.name
  1915.  
  1916.  
  1917.  
  1918. def DocTestSuite(module = None, globs = None, extraglobs = None, test_finder = None, **options):
  1919.     '''
  1920.     Convert doctest tests for a module to a unittest test suite.
  1921.  
  1922.     This converts each documentation string in a module that
  1923.     contains doctest tests to a unittest test case.  If any of the
  1924.     tests in a doc string fail, then the test case fails.  An exception
  1925.     is raised showing the name of the file containing the test and a
  1926.     (sometimes approximate) line number.
  1927.  
  1928.     The `module` argument provides the module to be tested.  The argument
  1929.     can be either a module or a module name.
  1930.  
  1931.     If no argument is given, the calling module is used.
  1932.  
  1933.     A number of options may be provided as keyword arguments:
  1934.  
  1935.     setUp
  1936.       A set-up function.  This is called before running the
  1937.       tests in each file. The setUp function will be passed a DocTest
  1938.       object.  The setUp function can access the test globals as the
  1939.       globs attribute of the test passed.
  1940.  
  1941.     tearDown
  1942.       A tear-down function.  This is called after running the
  1943.       tests in each file.  The tearDown function will be passed a DocTest
  1944.       object.  The tearDown function can access the test globals as the
  1945.       globs attribute of the test passed.
  1946.  
  1947.     globs
  1948.       A dictionary containing initial global variables for the tests.
  1949.  
  1950.     optionflags
  1951.        A set of doctest option flags expressed as an integer.
  1952.     '''
  1953.     if test_finder is None:
  1954.         test_finder = DocTestFinder()
  1955.     
  1956.     module = _normalize_module(module)
  1957.     tests = test_finder.find(module, globs = globs, extraglobs = extraglobs)
  1958.     if globs is None:
  1959.         globs = module.__dict__
  1960.     
  1961.     if not tests:
  1962.         raise ValueError(module, 'has no tests')
  1963.     
  1964.     tests.sort()
  1965.     suite = unittest.TestSuite()
  1966.     for test in tests:
  1967.         if len(test.examples) == 0:
  1968.             continue
  1969.         
  1970.         if not test.filename:
  1971.             filename = module.__file__
  1972.             if filename[-4:] in ('.pyc', '.pyo'):
  1973.                 filename = filename[:-1]
  1974.             
  1975.             test.filename = filename
  1976.         
  1977.         suite.addTest(DocTestCase(test, **options))
  1978.     
  1979.     return suite
  1980.  
  1981.  
  1982. class DocFileCase(DocTestCase):
  1983.     
  1984.     def id(self):
  1985.         return '_'.join(self._dt_test.name.split('.'))
  1986.  
  1987.     
  1988.     def __repr__(self):
  1989.         return self._dt_test.filename
  1990.  
  1991.     __str__ = __repr__
  1992.     
  1993.     def format_failure(self, err):
  1994.         return 'Failed doctest test for %s\n  File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err)
  1995.  
  1996.  
  1997.  
  1998. def DocFileTest(path, module_relative = True, package = None, globs = None, parser = DocTestParser(), encoding = None, **options):
  1999.     if globs is None:
  2000.         globs = { }
  2001.     else:
  2002.         globs = globs.copy()
  2003.     if package and not module_relative:
  2004.         raise ValueError('Package may only be specified for module-relative paths.')
  2005.     
  2006.     (doc, path) = _load_testfile(path, package, module_relative)
  2007.     if '__file__' not in globs:
  2008.         globs['__file__'] = path
  2009.     
  2010.     name = os.path.basename(path)
  2011.     if encoding is not None:
  2012.         doc = doc.decode(encoding)
  2013.     
  2014.     test = parser.get_doctest(doc, globs, name, path, 0)
  2015.     return DocFileCase(test, **options)
  2016.  
  2017.  
  2018. def DocFileSuite(*paths, **kw):
  2019.     '''A unittest suite for one or more doctest files.
  2020.  
  2021.     The path to each doctest file is given as a string; the
  2022.     interpretation of that string depends on the keyword argument
  2023.     "module_relative".
  2024.  
  2025.     A number of options may be provided as keyword arguments:
  2026.  
  2027.     module_relative
  2028.       If "module_relative" is True, then the given file paths are
  2029.       interpreted as os-independent module-relative paths.  By
  2030.       default, these paths are relative to the calling module\'s
  2031.       directory; but if the "package" argument is specified, then
  2032.       they are relative to that package.  To ensure os-independence,
  2033.       "filename" should use "/" characters to separate path
  2034.       segments, and may not be an absolute path (i.e., it may not
  2035.       begin with "/").
  2036.  
  2037.       If "module_relative" is False, then the given file paths are
  2038.       interpreted as os-specific paths.  These paths may be absolute
  2039.       or relative (to the current working directory).
  2040.  
  2041.     package
  2042.       A Python package or the name of a Python package whose directory
  2043.       should be used as the base directory for module relative paths.
  2044.       If "package" is not specified, then the calling module\'s
  2045.       directory is used as the base directory for module relative
  2046.       filenames.  It is an error to specify "package" if
  2047.       "module_relative" is False.
  2048.  
  2049.     setUp
  2050.       A set-up function.  This is called before running the
  2051.       tests in each file. The setUp function will be passed a DocTest
  2052.       object.  The setUp function can access the test globals as the
  2053.       globs attribute of the test passed.
  2054.  
  2055.     tearDown
  2056.       A tear-down function.  This is called after running the
  2057.       tests in each file.  The tearDown function will be passed a DocTest
  2058.       object.  The tearDown function can access the test globals as the
  2059.       globs attribute of the test passed.
  2060.  
  2061.     globs
  2062.       A dictionary containing initial global variables for the tests.
  2063.  
  2064.     optionflags
  2065.       A set of doctest option flags expressed as an integer.
  2066.  
  2067.     parser
  2068.       A DocTestParser (or subclass) that should be used to extract
  2069.       tests from the files.
  2070.  
  2071.     encoding
  2072.       An encoding that will be used to convert the files to unicode.
  2073.     '''
  2074.     suite = unittest.TestSuite()
  2075.     if kw.get('module_relative', True):
  2076.         kw['package'] = _normalize_module(kw.get('package'))
  2077.     
  2078.     for path in paths:
  2079.         suite.addTest(DocFileTest(path, **kw))
  2080.     
  2081.     return suite
  2082.  
  2083.  
  2084. def script_from_examples(s):
  2085.     """Extract script from text with examples.
  2086.  
  2087.        Converts text with examples to a Python script.  Example input is
  2088.        converted to regular code.  Example output and all other words
  2089.        are converted to comments:
  2090.  
  2091.        >>> text = '''
  2092.        ...       Here are examples of simple math.
  2093.        ...
  2094.        ...           Python has super accurate integer addition
  2095.        ...
  2096.        ...           >>> 2 + 2
  2097.        ...           5
  2098.        ...
  2099.        ...           And very friendly error messages:
  2100.        ...
  2101.        ...           >>> 1/0
  2102.        ...           To Infinity
  2103.        ...           And
  2104.        ...           Beyond
  2105.        ...
  2106.        ...           You can use logic if you want:
  2107.        ...
  2108.        ...           >>> if 0:
  2109.        ...           ...    blah
  2110.        ...           ...    blah
  2111.        ...           ...
  2112.        ...
  2113.        ...           Ho hum
  2114.        ...           '''
  2115.  
  2116.        >>> print script_from_examples(text)
  2117.        # Here are examples of simple math.
  2118.        #
  2119.        #     Python has super accurate integer addition
  2120.        #
  2121.        2 + 2
  2122.        # Expected:
  2123.        ## 5
  2124.        #
  2125.        #     And very friendly error messages:
  2126.        #
  2127.        1/0
  2128.        # Expected:
  2129.        ## To Infinity
  2130.        ## And
  2131.        ## Beyond
  2132.        #
  2133.        #     You can use logic if you want:
  2134.        #
  2135.        if 0:
  2136.           blah
  2137.           blah
  2138.        #
  2139.        #     Ho hum
  2140.        <BLANKLINE>
  2141.        """
  2142.     output = []
  2143.     for piece in DocTestParser().parse(s):
  2144.         if isinstance(piece, Example):
  2145.             output.append(piece.source[:-1])
  2146.             want = piece.want
  2147.             if want:
  2148.                 output.append('# Expected:')
  2149.                 [] += [ '## ' + l for l in want.split('\n')[:-1] ]
  2150.             
  2151.         want
  2152.         [] += [ _comment_line(l) for l in piece.split('\n')[:-1] ]
  2153.     
  2154.     while output and output[-1] == '#':
  2155.         output.pop()
  2156.         continue
  2157.         []
  2158.     while output and output[0] == '#':
  2159.         output.pop(0)
  2160.         continue
  2161.         output
  2162.     return '\n'.join(output) + '\n'
  2163.  
  2164.  
  2165. def testsource(module, name):
  2166.     '''Extract the test sources from a doctest docstring as a script.
  2167.  
  2168.     Provide the module (or dotted name of the module) containing the
  2169.     test to be debugged and the name (within the module) of the object
  2170.     with the doc string with tests to be debugged.
  2171.     '''
  2172.     module = _normalize_module(module)
  2173.     tests = DocTestFinder().find(module)
  2174.     test = _[1]
  2175.     test = test[0]
  2176.     testsrc = script_from_examples(test.docstring)
  2177.     return testsrc
  2178.  
  2179.  
  2180. def debug_src(src, pm = False, globs = None):
  2181.     """Debug a single doctest docstring, in argument `src`'"""
  2182.     testsrc = script_from_examples(src)
  2183.     debug_script(testsrc, pm, globs)
  2184.  
  2185.  
  2186. def debug_script(src, pm = False, globs = None):
  2187.     '''Debug a test script.  `src` is the script, as a string.'''
  2188.     import pdb
  2189.     srcfilename = tempfile.mktemp('.py', 'doctestdebug')
  2190.     f = open(srcfilename, 'w')
  2191.     f.write(src)
  2192.     f.close()
  2193.     
  2194.     try:
  2195.         if globs:
  2196.             globs = globs.copy()
  2197.         else:
  2198.             globs = { }
  2199.         if pm:
  2200.             
  2201.             try:
  2202.                 execfile(srcfilename, globs, globs)
  2203.             print sys.exc_info()[1]
  2204.             pdb.post_mortem(sys.exc_info()[2])
  2205.  
  2206.         else:
  2207.             pdb.run('execfile(%r)' % srcfilename, globs, globs)
  2208.     finally:
  2209.         os.remove(srcfilename)
  2210.  
  2211.  
  2212.  
  2213. def debug(module, name, pm = False):
  2214.     '''Debug a single doctest docstring.
  2215.  
  2216.     Provide the module (or dotted name of the module) containing the
  2217.     test to be debugged and the name (within the module) of the object
  2218.     with the docstring with tests to be debugged.
  2219.     '''
  2220.     module = _normalize_module(module)
  2221.     testsrc = testsource(module, name)
  2222.     debug_script(testsrc, pm, module.__dict__)
  2223.  
  2224.  
  2225. class _TestClass:
  2226.     """
  2227.     A pointless class, for sanity-checking of docstring testing.
  2228.  
  2229.     Methods:
  2230.         square()
  2231.         get()
  2232.  
  2233.     >>> _TestClass(13).get() + _TestClass(-12).get()
  2234.     1
  2235.     >>> hex(_TestClass(13).square().get())
  2236.     '0xa9'
  2237.     """
  2238.     
  2239.     def __init__(self, val):
  2240.         '''val -> _TestClass object with associated value val.
  2241.  
  2242.         >>> t = _TestClass(123)
  2243.         >>> print t.get()
  2244.         123
  2245.         '''
  2246.         self.val = val
  2247.  
  2248.     
  2249.     def square(self):
  2250.         """square() -> square TestClass's associated value
  2251.  
  2252.         >>> _TestClass(13).square().get()
  2253.         169
  2254.         """
  2255.         self.val = self.val ** 2
  2256.         return self
  2257.  
  2258.     
  2259.     def get(self):
  2260.         """get() -> return TestClass's associated value.
  2261.  
  2262.         >>> x = _TestClass(-42)
  2263.         >>> print x.get()
  2264.         -42
  2265.         """
  2266.         return self.val
  2267.  
  2268.  
  2269. __test__ = {
  2270.     '_TestClass': _TestClass,
  2271.     'string': '\n                      Example of a string object, searched as-is.\n                      >>> x = 1; y = 2\n                      >>> x + y, x * y\n                      (3, 2)\n                      ',
  2272.     'bool-int equivalence': '\n                                    In 2.2, boolean expressions displayed\n                                    0 or 1.  By default, we still accept\n                                    them.  This can be disabled by passing\n                                    DONT_ACCEPT_TRUE_FOR_1 to the new\n                                    optionflags argument.\n                                    >>> 4 == 4\n                                    1\n                                    >>> 4 == 4\n                                    True\n                                    >>> 4 > 4\n                                    0\n                                    >>> 4 > 4\n                                    False\n                                    ',
  2273.     'blank lines': "\n                Blank lines can be marked with <BLANKLINE>:\n                    >>> print 'foo\\n\\nbar\\n'\n                    foo\n                    <BLANKLINE>\n                    bar\n                    <BLANKLINE>\n            ",
  2274.     'ellipsis': "\n                If the ellipsis flag is used, then '...' can be used to\n                elide substrings in the desired output:\n                    >>> print range(1000) #doctest: +ELLIPSIS\n                    [0, 1, 2, ..., 999]\n            ",
  2275.     'whitespace normalization': '\n                If the whitespace normalization flag is used, then\n                differences in whitespace are ignored.\n                    >>> print range(30) #doctest: +NORMALIZE_WHITESPACE\n                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n                     27, 28, 29]\n            ' }
  2276.  
  2277. def _test():
  2278.     r = unittest.TextTestRunner()
  2279.     r.run(DocTestSuite())
  2280.  
  2281. if __name__ == '__main__':
  2282.     _test()
  2283.  
  2284.